package com.springboot.service.Impl;

import com.springboot.Exception.UserException;
import com.springboot.dao.userMapper;
import com.springboot.enums.enumOa;
import com.springboot.model.user;
import com.springboot.repository.userRepository;
import com.springboot.service.userService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class userServiceImpl implements userService {
    @Autowired
    private userMapper usermapper;
    @Autowired
    private userRepository userrepos;
    ;

    //  使用mabits
    @Override
    public void save(user userdata) {

        usermapper.insert(userdata);
    }

    //使用jpa
    @Override
    public Optional<user> find(long id) {
        return userrepos.findById(id);

    }

    @Override
    public List<user> finaByname(String name) {
        List<user> list = userrepos.findByUsernameAndAge(name, 1);
        return list;
    }

    @Override
    public List<user> userList() {
        return userrepos.findAll();
    }

    @Override
    public user saveuser(user userdata) {
        return userrepos.save(userdata);
    }

    @Override
    public Optional<user> findbyid(Long id) {

        return userrepos.findById(id);
    }

    @Override
    public void deletuser(Long id) {
        userrepos.deleteById(id);
    }

    @Override
    public user updateuser(user userdata) {
        return userrepos.save(userdata);
    }

    @Override
    public List<user> findbyage(Integer age) {
        return userrepos.findByAge(age);
    }

    @Override
    @Transactional
    public void inserttwo() {
        user usera = new user();
        usera.setAge(12);
        usera.setUsername("kongdan");
        user userb = new user();
        userb.setUsername("zhuliru");
        userb.setAge(13);
        userrepos.save(usera);
        userrepos.save(userb);

    }

    @Override
    public void exception(Long id) throws Exception {
        Optional<user> userdata = userrepos.findById(id);
        Integer age = userdata.get().getAge();
        if (age < 10) {
            throw new UserException(enumOa.PRIMARY_SCHOOLE);
        } else if (age > 10 && age < 16) {
            throw new UserException(enumOa.MIDDLE_SCHOOLE);
        } else {

        }
    }


}
